package com.zheng.upms.server.controller.manage;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.JsonUtil;
import com.zheng.common.validator.LengthValidator;
import com.zheng.upms.common.constant.UpmsResult;
import com.zheng.upms.common.constant.UpmsResultConstant;
import com.zheng.upms.dao.model.UpmsAgent;
import com.zheng.upms.dao.model.UpmsAgentExample;
import com.zheng.upms.dao.model.UpmsDict;
import com.zheng.upms.rpc.api.UpmsAgentService;
import com.zheng.upms.rpc.api.UpmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lvg EMIAL：<a href="mailto:weiguo.liang@gh-ca.com">weiguo.liang@gh-ca.com</a> <br>
 * @version 1.0 <br>
 * @Company: GH-CA<br>
 * @ClassName: UpmsAgentController <br>
 * @Description: 代理管理控制类 <br>
 * @date 2018/9/11 10:39<br>
 **/
@Controller
@Api(value = "代理管理", description = "代理管理")
@RequestMapping("/manage/agent")
public class UpmsAgentController  extends BaseController{

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsAgentController.class);

    @Autowired
    private UpmsAgentService upmsAgentService;
    @Autowired
    private UpmsApiService upmsApiService;

    @ApiOperation(value = "代理首页")
    @RequiresPermissions("upms:agent:read")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index() {
        return "/manage/agent/index.jsp";
    }

    @ApiOperation(value = "代理树列表")
    @RequiresPermissions("upms:agent:read")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        UpmsAgentExample upmsAgentExample = new UpmsAgentExample();
        UpmsAgentExample.Criteria criteria = upmsAgentExample.createCriteria();
        criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            upmsAgentExample.setOrderByClause(sort + " " + order);
        }
        if (StringUtils.isNotBlank(search)) {
            criteria.andNameLike("%" + search + "%");
        }
        List<UpmsAgent> rows = upmsAgentService.selectByExample(upmsAgentExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        return result;
    }

    @ApiOperation(value = "新增代理")
    @RequiresPermissions("upms:agent:create")
    @RequestMapping(value = "/create/{id}", method = {RequestMethod.GET})
    public String create(@PathVariable("id") int id, ModelMap modelMap) {
        if(StringUtils.isNotBlank(id+"")){
            UpmsAgent upmsAgent = upmsAgentService.selectByPrimaryKey(id);
            modelMap.put("pagent", upmsAgent);
        }
        UpmsAgentExample example = new UpmsAgentExample();
        example.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        List<UpmsAgent> upmsAgents = upmsAgentService.selectByExample(example);
        modelMap.put("upmsAgents", JsonUtil.object2Json(upmsAgents));
        //代理类型
        List<UpmsDict> agentTypeList = upmsApiService.selectUpmsDictByCode(Constant.UPMS_AGENT_TYPE);
        modelMap.put("agentTypeList", agentTypeList);
        //是否
        List<UpmsDict> yesNoList = upmsApiService.selectUpmsDictByCode(Constant.UPMS_YES_NO);
        modelMap.put("yesNoList", yesNoList);
        return "/manage/agent/create.jsp";
    }

    @ApiOperation(value = "新增代理")
    @RequiresPermissions("upms:agent:create")
    @ResponseBody
    @RequestMapping(value = "/create", method = {RequestMethod.POST})
    public Object create(UpmsAgent upmsAgent) {
        ComplexResult result = FluentValidator.checkAll()
                .on(upmsAgent.getName(), new LengthValidator(1, 120, "名称"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }
        long time = System.currentTimeMillis();
        upmsAgent.setCtime(time);
        upmsAgent.setCuser(getLoginUserName());
        int count = upmsAgentService.insertSelective(upmsAgent);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "删除代理")
    @RequiresPermissions("upms:agent:delete")
    @RequestMapping(value = "/delete/{ids}",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
//        int count = upmsAgentService.deleteByPrimaryKeys(ids);
        int count = upmsAgentService.deleteLogicByPrimaryKeys(ids,UpmsAgent.class,null);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "修改代理")
    @RequiresPermissions("upms:agent:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.GET})
    public String update(@PathVariable("id") int id, ModelMap modelMap) {
        UpmsAgent upmsAgent = upmsAgentService.selectByPrimaryKey(id);
        modelMap.put("agent", upmsAgent);
        if(upmsAgent.getPid()!=null){
            UpmsAgent parentUpmsAgent = upmsAgentService.selectByPrimaryKey(upmsAgent.getPid());
            modelMap.put("pagent", parentUpmsAgent);
        }
        UpmsAgentExample example = new UpmsAgentExample();
        example.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        List<UpmsAgent> upmsAgents = upmsAgentService.selectByExample(example);
        modelMap.put("upmsAgents", JsonUtil.object2Json(upmsAgents));
        //代理类型
        List<UpmsDict> agentTypeList = upmsApiService.selectUpmsDictByCode(Constant.UPMS_AGENT_TYPE);
        modelMap.put("agentTypeList", agentTypeList);
        //是否
        List<UpmsDict> yesNoList = upmsApiService.selectUpmsDictByCode(Constant.UPMS_YES_NO);
        modelMap.put("yesNoList", yesNoList);
        return "/manage/agent/update.jsp";
    }

    @ApiOperation(value = "修改代理")
    @RequiresPermissions("upms:agent:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public Object update(@PathVariable("id") int id, UpmsAgent upmsAgent) {
        ComplexResult result = FluentValidator.checkAll()
                .on(upmsAgent.getName(), new LengthValidator(1, 20, "名称"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }
        upmsAgent.setId(id);
        int count = upmsAgentService.updateByPrimaryKeySelective(upmsAgent);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

}
